package com.burgeon.backend.SHOPBACKEND.controller;


import com.burgeon.backend.SHOPBACKEND.entity.WxChatImage;
import com.burgeon.backend.SHOPBACKEND.entity.weixin.TextMessage;
import com.burgeon.backend.SHOPBACKEND.service.AWechatService;
import com.burgeon.backend.Util.menu.WeChatInfo;
import com.burgeon.backend.Util.wechatUtil.CheckUtil;
import com.burgeon.backend.Util.wechatUtil.WeGetAccessToken;
import com.burgeon.backend.Util.wechatUtil.WechatMessageUtil;
import com.burgeon.backend.stsutil.ResponseResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Map;

@Controller
public class wehcatController extends BaseController{

    private static Logger log = Logger.getLogger(wehcatController.class);

    @Autowired
    AWechatService wechatService;

    @RequestMapping("/wechat")
    public void cgi(HttpServletRequest request, HttpServletResponse response,PrintWriter out) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        try {
            if (isGet) {
                String signature = request.getParameter("signature");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");
                log.info("signature = "+signature+" , timestamp = "+timestamp+ " , nonce = "+nonce+ " , echostr = "+echostr);
                if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                    out.print(echostr);
                }
            }else{
                // 进入POST聊天处理
                // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                // 接收消息并返回消息
                response.setContentType("text/xml,charset=utf-8");
                Map<String, String> requestMap = WechatMessageUtil.xmlToMap(request);
                log.info(">>>>>>>>>>>>>"+requestMap);
                // 发送方帐号（open_id）
                String fromUserName = requestMap.get("FromUserName");
                // 公众帐号
                String toUserName = requestMap.get("ToUserName");
                TextMessage textMessage = new TextMessage();
                textMessage.setMsgType("text");
                textMessage.setToUserName(fromUserName);
                textMessage.setFromUserName(toUserName);
                textMessage.setCreateTime(System.currentTimeMillis());
                textMessage.setContent("success");
                String responseMessage = WechatMessageUtil.textMessageToXml(textMessage);

                out.print(responseMessage);
                out.flush();
                //处理请求
//              String rm = wechatService.processRequest(request);
                String rm = wechatService.acceptMessage(requestMap, response, WeChatInfo.token);
                out.print(rm);

                // 响应消息
//              PrintWriter out = response.getWriter();
//              out.print(result);
                out.close();
            }
        } catch (Exception ex) {
            log.error("微信帐号接口配置失败！", ex);
            ex.printStackTrace();
        }
    }





//    /**
//     * * 验证微信服务器
//     * @param response
//     * @param signature
//     * @param timestamp
//     * @param nonce
//     * @param echostr
//     */
//    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
//    public void wechatService(
//            PrintWriter out, HttpServletResponse response,
//            @RequestParam(value = "signature", required = false) String signature,
//            @RequestParam String timestamp,
//            @RequestParam String nonce,
//            @RequestParam String echostr) {
//        System.err.println("token");
//        System.err.println("微信signature=="+signature);
//        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
//            out.print(echostr);
//        }
//    }

    /**
     * 接收来自微信发来的消息
     * @param out
     * @param request
     * @param response
     */
//    @ResponseBody
//    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
//        public void wechatServicePost(PrintWriter out, HttpServletRequest request, HttpServletResponse response,
//                                      HttpSession session
//    ) throws IOException {
//
//        response.setCharacterEncoding("ISO8859_1");
//        request.setCharacterEncoding("UTF-8");
////      System.err.println("接收到数据===="+request);
//
//        response.setContentType("text/xml,charset=utf-8");
//        out.print("success");
//        out.flush();
//            //处理请求
////       String rm = wechatService.processRequest(request);
//         wechatService.messRequest(request,session);
////       System.err.println(rm);
////       //将发送内容转码
////       String responseMessage = new String(
////                    rm.getBytes(StandardCharsets.UTF_8), "ISO8859_1");
////       再将格式转换过来
////
////       String responseMessage = wechatService.processRequest(request);
////       System.err.println(rm);
////
////       log.info("vvvvvvvvvvvvvvvvvvvvvvvv"+responseMessage);
////       log.info(rm);
////       相应
////       print方法可以将各种类型的数据转换成字符串的形式输出
////       out.print(responseMessage);
////       直面意思就是刷新printwriter流的缓冲区
////       将缓冲区的数据强制输出，用于清空缓冲区，
////       若直接调用close()方法，则可能会丢失缓冲区的数据。
////       所以通俗来讲它起到的是刷新的作用。
////       return "index.html";
////       return View("ViewName");
////       重定向到
//    }


    /***
     * 接收来自安卓的导购回复消息（文本消息）
     */
    @ResponseBody
    @RequestMapping("/androidText")
    public ResponseResult MessageByAndroid(String contest, String openid, String daoId) {
        System.err.println(openid);
        wechatService.messAndroid(contest,openid,daoId);
        return new ResponseResult(200);
    }

    /***
     * 接收来自安卓的导购回复消息（图片消息）
     */
    @ResponseBody
    @RequestMapping("/androidImage")
    public ResponseResult ImageByAndroid(String openid,String contest) {
        // wechatService.Android(openid,contest);
        return new ResponseResult(200);
    }


    /**
     * 获取微信的消息纪录
     */
//    @ResponseBody
//    @RequestMapping(value = "/sendCondition")
//    public ResponseResult<String> sendCondition(String startTime,String endTime) throws ParseException {
////        if("null".equals(startTime)){
////            return new ResponseResult<Strin;
////        }
//        JSONObject data = wechatService.getSendCondition(startTime,endTime);
//        return new ResponseResult<String>(SUCCESS,data.toString());
//    }

    /**
     * 获取微信用户列表信息
     */
//    @ResponseBody
//    @RequestMapping(value = "/getAllUsersInfo")
//    public ResponseResult<Void> getAllUsersInfo(){
//        wechatService.getAllUsersInfo();
//        return new ResponseResult<Void>(SUCCESS);
//    }


    /**
     * 获取微信用户信息
     */
//    @ResponseBody
//    @RequestMapping(value = "/getUserInfo")
//    public ResponseResult<WeiXinUser> getUserInfo(String openId) throws ParseException {
//        long startTime = System.currentTimeMillis();    //获取开始时间
//        String accessToken = WeGetAccessToken.getAccessToken();
//        WeiXinUser data = wechatService.getUserInfo(accessToken,openId);
//        long endTime = System.currentTimeMillis();    //获取结束时间
//             //输出程序运行时间
//        return new ResponseResult<>(200,data);
//    }


    /**
     * 获取微信的用户
     */
//    @ResponseBody
//    @RequestMapping(value = "getUsers")
//    public ResponseResult<List<String>> getUsers() throws ParseException {
//
//        List<String> data = wechatService.getAllWeiXinUser();
//        return new ResponseResult<List<String>>(200,data);
//    }







//    @ResponseBody
//    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
//    public void wechatkefuPost(
//            PrintWriter out,
//            HttpServletRequest request,
//            HttpServletResponse response) throws UnsupportedEncodingException {
////
////         out.print(responseMessage);
////        out.flush();
//
//    }









//    @ApiOperation(value = "1.7 客服接口-发送消息")
//
//    @GetMapping(value = "/sendCustomerProviderNews")
//
//    public void sendCustomerProviderNews() {
//
//        //1.客服接口-发送文本消息
//
////        customerProviderService.sendCustomerProviderNews("1");
//
//        //2.发送图片消息
//
//        customerProviderService.sendCustomerProviderNews("2");
//
//        //7.发送菜单消息
//
////        customerProviderService.sendCustomerProviderNews("7");
//
//
//
//
//
//    }




    /**
     * 这个是加入微信依赖包的
     */
    //    //微信配置服务器 验证
//    @RequestMapping(value="/wxserver",method={RequestMethod.GET})
//    public  void check(HttpServletRequest request, HttpServletResponse response)  {
//
//        //微信服务器get传递的参数
//        String signature = request.getParameter("signature");
//
//        String timestamp = request.getParameter("timestamp");
//
//        String nonce = request.getParameter("nonce");
//
//        String echostr = request.getParameter("echostr");
//
//        //微信工具服务类
//
//        WxMpService wxService=new WxMpServiceImpl();
//
//        //注入token的配置参数
//
//        /**
//         * 生产环境 建议将WxMpInMemoryConfigStorage持久化
//         */
//        WxMpInMemoryConfigStorage wxConfigProvider=new WxMpInMemoryConfigStorage();
//
//        //注入token值
//        wxConfigProvider.setToken("gaolingling");
//
//        wxService.setWxMpConfigStorage(wxConfigProvider);
//
//        //验证token跟微信配置的是否一样
//        boolean flag=wxService.checkSignature(timestamp, nonce, signature);
//        System.err.println(flag);
//
//        PrintWriter out= null;
//
//        try {
//
//            out = response.getWriter();
//
//        } catch (IOException e) {
//
//            e.printStackTrace();
//
//        }
//
//        if(flag){
//
//            out.print(echostr);
//
//        }
//
//        out.close();
//
//    }


//    /**
//     * @param request
//     * @return
//     * @description 验证微信的token
//     * @author zhou
//     * @date 2019/6/1
//     */
//    @GetMapping("/tokenVerification")
//    public void tokenVerification(HttpServletRequest request,
//                                  HttpServletResponse response) {
//        //微信加密签名
//        String signature = request.getParameter("signature");
//        //时间戳
//        String timestamp = request.getParameter("timestamp");
//        //随机数
//        String nonce = request.getParameter("nonce");
//        //随机字符串
//        String echostr = request.getParameter("echostr");
//        try {
//            //获取sha1加密
//            String sha1Result = SHA1.getSHA1(wxOfficialsAccountConfiguration.getToken(),
//                    timestamp, nonce);
//            //判断和签名是否一致
//            if (sha1Result.equals(signature)) {
//                response.getWriter().write(echostr);
//            } else {
//                throw new WeChatOaException(WeChatOaErrorEnum.NOT_FROM_WECHAT);
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//    }




//    @GetMapping(value = "/sendCondition")
//
//    public void sendCondition() throws ParseException {
//
//
//
//        //1.获取AccessToken
//
//        String accessToken = WeiXinParamesUtil.getAccessToken("customerService");
//
//        String url = "https://api.weixin.qq.com/customservice/msgrecord/getmsglist?access_token=ACCESS_TOKEN";
//
//        url = url.replace("ACCESS_TOKEN", accessToken);
//
//
//
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        Date date = simpleDateFormat.parse("2020-02-11 8:45:25");
//
//        long startTime = date.getTime()/1000;
//
//        Date date1 = simpleDateFormat.parse("2020-02-11 21:45:26");
//
//        long endTime = date1.getTime()/1000;
//
//
//
//        String jsonStr = "  {\n" +
//
//                "      \"starttime\" : "+String.valueOf(startTime)+",\n" +
//
//                "      \"endtime\" : "+String.valueOf(endTime)+",\n" +
//
//                "      \"msgid\" : 1,\n" +
//
//                "      \"number\" : 10000 \n" +
//
//                "}";
//
//
//
//        JSONObject jsonObject = SendRequest.sendPost(url, jsonStr);
//
//        System.out.println("1111-----" + jsonObject);
//
//    }


}
